<template>
  <div style="padding-top:100px">
    <div class="app-title-container title-position">
      <modules-title :titleName="auditData.Flow.Name">
        <template slot="btn">
          <el-button class="filter-item" plain="" size="small" @click="handleBack">返回
          </el-button>
          <!-- <el-button type="primary" size="small" @click="handlUndo"
            v-if="formTable.reserve_sample_destroy.destroy_check &&  formTable.reserve_sample_destroy.destroy_check.Cancelable">
            撤销
          </el-button>
          <el-button type="primary" size="small"
            v-if="formTable.reserve_sample_destroy.status === 0" @click="handlApproval()">
            审批
          </el-button> -->
          <approval :affair.sync="auditData" :is-text="false" @refresh="refreshData"
            @submit="onSubmit" @toEdit="toEdit" @cancel="onCancel" />
        </template>
      </modules-title>
    </div>
    <div style="padding:20px">
      <item-title title="基础数据" :borderShow="false" />

      <el-form label-width="110px" size="small" label-position="left">
        <el-row :gutter="80">
          <el-col :span="8">
            <el-form-item label="当前状态：">
              {{handlStatus(formTable.reserve_sample_destroy.status)}}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="销毁单据：">
              {{formTable.reserve_sample_destroy.destroy_no}}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="创建人：">
              {{formTable.reserve_sample_destroy.creator_name}}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="创建时间：">
              <span v-if="formTable.reserve_sample_destroy.created_at">
                {{dateFormat1('yyyy-mm-dd ',formTable.reserve_sample_destroy.created_at)}}
              </span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="销毁人：">
              {{formTable.reserve_sample_destroy.destroy_user_name}}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="监督人：">
              {{formTable.reserve_sample_destroy.supervision_user_name}}
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="formTable.reserve_sample_destroy.status === 4">
            <el-form-item label="销毁日期：">
              <span v-if="formTable.reserve_sample_destroy.destroy_time">
                {{dateFormat1('yyyy-mm-dd ',formTable.reserve_sample_destroy.destroy_time)}}</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <item-title title="销毁明细" :borderShow="false" />
      <el-table :data="formTable.sample_destroy_info" style="margin-bottom:20px" class="table1"
        border size="medium">
        <el-table-column prop="sample_info.name" label="样品名称" align="center" />
        <el-table-column label="样品类别" align="center">
          <template #default="{row}">
              <span v-if="row.sample_info.sample_type_info">
                {{row.sample_info.sample_type_info.same_type_name	}}
              </span>
          </template>
        </el-table-column>
        <el-table-column label="批号" align="center">
          <template #default="{row}">
            <span v-if="row.sample_info"> {{handlBatch(row.sample_info.batch_info)}}</span>
          </template>
        </el-table-column>
        <!--          <el-table-column prop="sample_info.attr" label="规格" align="center"/>-->
        <el-table-column prop="project_name" label="所属项目" align="center" />
        <el-table-column label="留样日期" align="center">
          <template #default="{row}">
            <span v-if="row.reserve_sample_time">
              {{dateFormat1('yyyy-mm-dd ',row.reserve_sample_time)}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="destroy_num" label="留样数量" align="center" />
        <el-table-column prop="destroy_num" label="销毁数量" align="center" />
        <el-table-column prop="reason" label="销毁原因" align="center" :show-overflow-tooltip="true" />
        <el-table-column v-if="formTable.reserve_sample_destroy.status === 4" prop="destroy_way"
          label="销毁方式" align="center" />

      </el-table>

      <item-title title="审批记录" :borderShow="false" />
      <comment-view :datas="auditData" />

    </div>
    <el-dialog title="销毁审批" :visible.sync="open" width="600px" append-to-body :before-close="cancel"
      :close-on-click-modal="false" v-if="open">
      <el-form ref="formOpen" :model="formOpen" :rules="rules" label-width="100px" size="small">
        <el-form-item label="审批结果">
          <el-radio-group v-model="formOpen.check_status">
            <el-radio v-for="(item,index) in buttonList" :key="index" :label="item.Type">
              {{item.Name}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审批意见">
          <el-input type="textarea" :rows="2" v-model="formOpen.check_advice"
            placeholder="请输入审批意见" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button plain size="small" @click="cancel">取 消
        </el-button>
        <el-button size="small" type="primary" @click="submitForm">
          确定
        </el-button>
      </div>

    </el-dialog>
  </div>
</template>

<script>
import { approvalDetail, approvalCheck } from "@/api/sampleManagement";

export default {
  name: "approvallo",
  data() {
    return {
      value1: [],
      formTable: {
        reserve_sample_destroy: {
          destroy_check: {}
        },
        sample_destroy_info: []
      },
      options: [
        { value: -1, label: "全部" },
        { value: 0, label: "审批中" },
        { value: 1, label: "已拒绝" },
        { value: 2, label: "待销毁" },
        { value: 3, label: "销毁确认" },
        { value: 4, label: "已销毁" },
        { value: 5, label: '已撤销' },
        { value: 6, label: '已回退' },
      ],
      auditData: {
        Flow:{}
      },
      auditButtonName: "审批",
      isAudit: false,
      userInfo: null,
      open: false,
      formOpen: {
        check_advice: "",
        check_status: "Next"
      },
      rules: {
        check_advice: [
          { required: true, message: "请输入审批意见", trigger: "blur" }
        ]
      },
      buttonList: []
    };
  },
  //是计算属性，也可以理解为一个方法。
  computed: {
    handlStatus() {
      return function(val) {
        let a = "";
        this.options.forEach(element => {
          if (val === element.value) {
            a = element.label;
          }
        });
        return a;
      };
    },
    handlBatch() {
      return function(val) {
        let str = ''
        if (val) {
          for (let i = 0; i < val.length; i++) {
            str += val[i].sample_batch
            if (i !== val.length - 1) {
              str = str + '、'
            }
          }
        }
        return str
      }
    }
  },

  //属性是手动定义的所需监听的值
  watch: {},

  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.handlApprovalDetail();
    this.userInfo = this.$store.getters.userInfo;
    if (this.$route.query) {
      this.getAuditData(this.$route.query.f_id);
    }
  },

  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {},

  //是Vue实例对象上绑定的方法，供当前Vue组件作用域内使用，
  methods: {
    //返回
    handleBack() {
      this.$route.params.refresh = true;
      this.$router.go(-1);

    },

    //获取详情数据
    handlApprovalDetail() {
      approvalDetail(this.$route.query.f_id).then(res => {
        if (res.code === 200) {
          this.formTable = res.data;
        }
      });
    },

    handlApproval() {
      this.open = true;
    },

    // 撤销
    handlUndo() {
      const subdata = {
        flow_id: this.$route.query.f_id,
        model_type: "RetainDestroy"
      };
      this.$comFun.cancelFunc(subdata)
        .then(() => {
          this.$message({
            type: "success",
            message: "已撤销"
          });
          this.handlApprovalDetail();
        })
        .catch(err => {
          this.$message.error(err);
        });
    },

    getAuditData(id) {
      this.$api.PROJECT_START_CHECK_DETAIL(id).then(res => {
        if (res.code === 200) {
          this.auditData = res.data;
          this.getButton();
        }
      });
    },
    getButton() {
      if (
        this.auditData.State !== "Done" ||
        this.auditData.State !== "Refuse"
      ) {
        if (this.auditData.Next && this.auditData.Next.length) {
          for (let i = 0; i < this.auditData.Next.length; i++) {
            const data = this.auditData.Next[i];
            const index = data.Staffs.findIndex(
              a => a === this.userInfo.user.id
            );
            if (index !== -1) {
              this.isAudit = true;
              this.auditButtonName = data.ItemName;
              this.buttonList = data.Buttons || [];
              let sss = this.buttonList.findIndex(a => a.Type == "Cancel");
              if (sss !== -1) {
                this.buttonList.splice(sss, 1);
              }
              break;
            }
          }
        }
      }
    },
    cancel() {
      this.formOpen = {
        check_advice: "",
        check_status: 1
      };
      this.open = false;
    },
    submitForm() {
      this.$refs.formOpen.validate(valid => {
        if (valid) {
          let data = {},
            msg = "";
          data = {
            id: this.formTable.reserve_sample_destroy.id,
            check_status: this.formOpen.check_status,
            check_advice: this.formOpen.check_advice
          };
          msg = "审批成功";
          approvalCheck(data).then(res => {
            if (res.code === 200) {
              this.$message.success(msg);
              this.cancel();
              this.handlApprovalDetail();
            } else {
              this.$message.error(res.msg);
            }
          });
        } else {
          return false;
        }
      });
    },
    refreshData() {
      this.handlApprovalDetail();
    },
    toEdit(affairs) {
      this.$router.push({
        path: "/sampleManagement/destruction/create",
        query: { s_id: this.formTable.reserve_sample_destroy.id }
      });
    },
    // affairsId, stepId , type  //选择类型, template //备注, RejectStepId  //步骤id
    onSubmit(affairsId, stepId, type, template, RejectStepId, callback) {
      console.log(affairsId, stepId, type, template, RejectStepId);
      const subdata = {
        id: this.formTable.reserve_sample_destroy.id,
        check_status: type,
        check_advice: template.Remark,
        step_id: RejectStepId,
        Files: template.Files
      };
      approvalCheck(subdata).then(res => {
        if (res.code === 200) {
          this.$message.success("审批成功");
          this.cancel();
          this.handlApprovalDetail();
          this.getAuditData(this.$route.query.f_id);
          callback(true);
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    onCancel(affairsId, stepId, type, template, RejectStepId, callback) {
      const subdata = {
        flow_id: this.$route.query.f_id,
        model_type: 'RetainDestroy'
      };
      this.$comFun.cancelFunc(subdata)
        .then(() => {
          callback(true);
          this.$message({
            type: "success",
            message: "已撤销"
          });
          this.handlApprovalDetail();
          this.getAuditData(this.$route.query.f_id);
          callback(true);
        })
        .catch(err => {
          this.$message.error(err);
        });
    }
  }
};
</script>

<style scoped>
/* @import url(); 引入css类 */
::v-deep .box_card {
  border: none !important;
}
</style>
